// packageC/hotel/demand-list/demand-list.js
const app = getApp()
import { formatDate, formatTime, dateRange, timeDiff } from '../../../utils/util'
import { roomTypeEnum, demandReceivingOrderStatusEnum, demandPayStatusEnum } from '../../../utils/dataEnum'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    roomTypeEnum,
    demandReceivingOrderStatusEnum,
    demandPayStatusEnum,
    currentHour: 0,
    // 请求参数对象
    queryObj:{
      page: 0,
      page_size: 5
    },
    // 总数量，用来实现分页
    total: 0,
    // 是否正在请求数据
    isloading: false,
    finished: false
  },

  /**
   * 获取需求列表
   * @param {Function} callback 
   */
  getDemandList: function(callback) {
    const urlStr = app.getNetAddresss('plugin.hotel.frontend.hotel.hotelDemand.get-list')
    const _this = this
    wx.showLoading({ title: '加载中...' })
    app._getNetWork({
      url: urlStr,
      data: {
        limit: this.data.queryObj.page_size,
        offset: this.data.list.length
      },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          let resList = [...resData.data.list]
          const nowStr = formatTime(new Date())
          _this.setData({
            total: resData.data.count
          })
          resList.forEach(item => {
            // 入住时间
            item.timeRange = dateRange(item.start_check_in_time, item.end_check_in_time, true)
            // 待接单，接单半小时内显示接单倒计时
            if (item.receiving_order_status == 1 && item.status == 1) {
              const diffMillisecond = timeDiff(nowStr, item.valid_time, 'millisecond')
              if (diffMillisecond > 0) {
                item.receivingCountDown = diffMillisecond
              }
            }
            // 已接单&待支付状态，接单半小内显示支付倒计时
            else if (item.receiving_order_status == 2 && item.status == 1) {
              const diffMillisecond = timeDiff(nowStr, item.valid_time, 'millisecond')
              if (diffMillisecond > 0) {
                item.payCountDown = diffMillisecond
              }
            }
          })
          _this.setData({ 
            list: [..._this.data.list, ...resList]
          })
          _this.setData({
            finished: _this.data.list.length >= _this.data.total
          })
        } else {
          app.tips(resData.msg || '数据加载失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        callback && callback()
      }
    })
  },

  /**
   * 跳转到需求详情页
   * @param {Object} e 
   */
  goDetail: function(e) {
    const { id } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/packageC/hotel/demand-detail/demand-detail?id=' + id,
    })
  },

  /**
   * 跳转到普通酒店订单详情
   * @param {Object} e 
   */
  goPay: function(e) {
    const { order_id, valid_time } = e.currentTarget.dataset.item
    if (!order_id) {
      app.tips('无法获取订单id！')
      return
    }
    const nowStr = formatTime(new Date())
    const diffMillisecond = timeDiff(nowStr, valid_time,  'millisecond')
    if (diffMillisecond == 0) {
      app.tips('订单超时！')
      return
    }
    wx.navigateTo({
      url: '/packageA/member/orderdetail/orderdetail?orderType=hotel&order_id=' + order_id,
    })
  },

  /**
   * 查看一口价酒店
   * @param {Object} e 
   */
  goToFixedPrice: function(e) {
    const now = new Date()
    const currentHour = now.getHours()
    if (currentHour < 20) {
      app.tips('每晚20点-24点才可以订购酒店的一口价房间！')
      return
    }
    const endNow = new Date()
    const timeStamp = endNow.getTime()
    endNow.setTime(timeStamp + 24 * 60 * 60 * 1000)
    const start_time = formatDate(now)
    const end_time = formatDate(endNow)
    wx.navigateTo({
      url: '/packageC/hotel/HotelSearch/HotelSearch?start=' + start_time + '&end=' + end_time + '&price=0&star=0&isFixedPrice=1'
    });
  },

  /**
   * 跳转到发布酒店需求
   */
  goRelease: function() {
    wx.navigateTo({
      url: '/packageC/hotel/release-demand/release-demand',
    })
  },

  /**
   * 页面刷新
   * @param {Function} callback 回调函数
   */
  refreshPage(callback) {
    this.setData({
      list: [],
      queryObj: {
        page: 0,
        page_size: 5
      },
      total: 0,
      isloading: false,
      finished: false
    })
    this.getDemandList(callback)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const now = new Date()
    const currentHour = now.getHours()
    this.setData({ currentHour })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDemandList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshPage(() => wx.stopPullDownRefresh())
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if ((this.data.queryObj.page + 1) * this.data.queryObj.page_size >= this.data.total){
      wx.showLoading({
        title: '数据加载完毕！',
      })
      wx.hideLoading() // 关闭loading
      return
    }
    if(this.data.isLoading) return
    this.setData({
      // 让页码值自增 +1
      page: this.data.queryObj.page += 1
    })
    // 重新获取列表数据
    this.getDemandList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})